package com.tc.gateway.tunnel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

import com.tc.util.*;

public class MultiTunnelServer extends MultiConnection implements TunnelServer {
	
	OutputStream stream;

	
	public MultiTunnelServer(final OutputStream stream) throws IOException {
		super(true);
		this.stream = stream;
	}
	public boolean started(){
		return ts != null;
	}
	/* (non-Javadoc)
	 * @see com.tc.assistance.tunnel.TunnelOutput#write(byte[], int, int)
	 */
	public void write(byte[] buffer, int offset, int len){
		if(!started())
			return;
		try {
			getOutputStream().write(buffer, offset, len);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}
	public void stop(){
		ts.interrupt();
		ts = null;
	
	}
	Thread ts;
	public void start(){
		ts = new Thread(){

			@Override
			public void run() {
				
				super.run();
				
				try {
				    byte[] buf = new byte[1024];

	                


					while(true){
						  int l = server.getInputStream().read(buf);
						  System.err.println(DataUtil.hex(buf, 0, l));
						   stream.write(buf,  0,l);

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println(e.getMessage());
				}
			}
			
		};
		ts.start();
	}
	static public void main(String[] s) throws IOException{
		FileOutputStream ss = new FileOutputStream("f:/gg.txt");
		MultiTunnelServer t = new MultiTunnelServer(ss);
		
		t.start();
//		try {
//			t.getOutputStream().write("ggggg".getBytes(), 0, 5);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		MultiCast mc = new MultiCast("228.9.6.9", 9999, false);
//		int i = 0;
//		while(true){
//			if(i == 10000)
//				break;
//			byte[] buf = new byte[1000];
//			
//		try {
//			 mc.getOutputStream().write((i++ + "").getBytes());
//			 Thread.sleep(150);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	}
}
